import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-04-08
 * Time: 21:34
 */
class MyTimer {
    static class Task implements Comparable<Task> {
        private Runnable commend;
        private long time;
        public Task(Runnable commend, long time) {
            this.commend = commend;
            this.time = System.currentTimeMillis() + time;
        }
        public void run() {
            commend.run();
        }

        @Override
        public int compareTo(Task o) {
            return (int) (this.time - o.time);
        }
    }
    private static PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
    static class Worker extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Task task = queue.take();
                    long curTime = System.currentTimeMillis();
                    if(task.time > curTime) {
                        synchronized (this) {
                            this.wait(task.time - curTime);
                        }
                    }else {
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public MyTimer() {
        Worker worker = new Worker();
        worker.start();
    }
    public void schedule(Runnable runnable, long time) {
        Task task = new Task(runnable,time);
        queue.put(task);
        this.notify();
    }
}
public class Demo3 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer");
            }
        },3000);
    }
}
